package com.sat.goods.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sat.goods.dao.BrandMapper;
import com.sat.goods.pojo.Brand;
import com.sat.goods.service.BrandService;
import entity.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public List<Brand> findAll() {
        return brandMapper.selectAll();
    }

    @Override
    public Brand findById(Integer id) {
        return brandMapper.selectByPrimaryKey(id);
    }

    @Override
    public void add(Brand brand) {
        brandMapper.insert(brand);
    }

    @Override
    public void update(Brand brand) {
        brandMapper.updateByPrimaryKeySelective(brand);
    }

    @Override
    public void delete(Integer id) {
        brandMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Brand> searchByBrand(Brand brand) {
        Example example = example(brand);
        List<Brand> brandList = brandMapper.selectByExample(example);
        return brandList;
    }

    @Override
    public PageResult<Brand> findPage(Integer page, Integer size) {

        Page<Brand> brandPage  = PageHelper.startPage(page, size);
        List<Brand> brandList = brandMapper.selectAll();
        PageResult<Brand> pageResult = new PageResult<>();

        pageResult.setTotal(brandPage.getTotal());
        pageResult.setRows(brandPage.getResult());
        return pageResult;
    }

    @Override
    public PageResult<Brand> findPage(Integer page, Integer size, Brand brand) {
        Page<Brand> brandPage = PageHelper.startPage(page, size);
        Example example = example(brand);
        brandMapper.selectByExample(example);

        PageResult<Brand> pageResult = new PageResult<>();
        pageResult.setTotal(brandPage.getTotal());
        pageResult.setRows(brandPage.getResult());
        return pageResult;
    }

    @Override
    public List<Brand> findBrandByCategoryId(Integer categoryId) {

        List<Brand> brands = brandMapper.findBrandByCategoryId(categoryId);
        return brands;
    }





    private Example example(Brand brand){
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();
        if(brand != null){
            if(!StringUtils.isEmpty(brand.getName())){
                criteria.andLike("name","%"+brand.getName()+"%");
            }
            if(!StringUtils.isEmpty(brand.getLetter())){
                criteria.andEqualTo("letter",brand.getLetter());
            }
        }
        return example;
    }

}
